/*
 * @Author: Wangjun
 * @Date: 2023-09-22 20:47:10
 * @LastEditTime: 2023-09-27 10:27:02
 * @LastEditors: Wangjun
 * @Description:
 * @FilePath: \xr_node_calcd:\go\src\gitee.com\haodreams\libs\ds\row.go
 * hnxr
 */
package ds

import (
	"io"
	"strconv"
)

type Row[N number] struct {
	ID     int
	Key    string
	fields []*N
}

/**
 * @description: 初始化
 * @param {int} l
 * @return {*}
 */
func (m *Row[N]) Setup(id int, nColumn int) {
	if cap(m.fields) < nColumn {
		m.fields = make([]*N, nColumn)
	} else {
		m.fields = m.fields[:nColumn]
	}
	m.ID = id
	for i := 0; i < nColumn; i++ {
		m.fields[i] = nil
	}
}

func (m *Row[N]) Reset() {
	for i := range m.fields {
		m.fields[i] = nil
	}
}

/**
 * @description: 设置全部的值
 * @param {[]*N} vals
 * @return {*}
 */
func (m *Row[N]) SetValues(vals []*N) {
	copy(m.fields, vals)
}

func (m *Row[N]) Set(idx int, v *N) {
	if idx >= len(m.fields) || idx < 0 {
		return
	}
	m.fields[idx] = v
}

func (m *Row[N]) Value(idx int) *N {
	if idx >= len(m.fields) || idx < 0 {
		return nil
	}
	return m.fields[idx]
}

func (m *Row[N]) SetValue(idx int, v *N) {
	if idx >= len(m.fields) || idx < 0 {
		return
	}
	m.fields[idx] = v
}

func (m *Row[N]) WriteTo(w io.Writer, writeKey bool) {
	w.Write([]byte(strconv.Itoa(m.ID)))
	if writeKey {
		w.Write([]byte(","))
		w.Write([]byte(m.Key))
	}
	w.Write([]byte(","))

	for i, v := range m.fields {
		if i == 0 {
			if v != nil {
				w.Write([]byte(strconv.FormatFloat(float64(*v), 'f', -1, 64)))
			}
		} else {
			w.Write([]byte(","))
			if v != nil {
				w.Write([]byte(strconv.FormatFloat(float64(*v), 'f', -1, 64)))
			}
		}
	}
	w.Write([]byte("\n"))
}
